package com.zyj.exoplayerdemo

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.google.android.exoplayer2.ExoPlayer
import com.google.android.exoplayer2.MediaItem
import com.google.android.exoplayer2.Player
import com.google.android.exoplayer2.SimpleExoPlayer
import com.google.android.exoplayer2.upstream.RawResourceDataSource
import com.zyj.exoplayerdemo.databinding.ActivityPlayMp3Binding

class PlayMp3Activity : AppCompatActivity() {

    private lateinit var binding: ActivityPlayMp3Binding

    private var mExoPlayer: ExoPlayer? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityPlayMp3Binding.inflate(layoutInflater)
        setContentView(binding.root)

        mExoPlayer = SimpleExoPlayer.Builder(this).build().apply {
            repeatMode = Player.REPEAT_MODE_OFF  //关闭循环播放
            volume = 0.5f
            addListener(mPlayerListener)
        }

        binding.loadLocal.setOnClickListener {
            //加载本地资源
            val uri = RawResourceDataSource.buildRawResourceUri(R.raw.mp31)
            val mediaItem: MediaItem = MediaItem.fromUri(uri)
            mExoPlayer?.setMediaItem(mediaItem)
            mExoPlayer?.prepare()
        }

        //加载网络资源
        binding.loadNet.setOnClickListener {
            val mediaItem: MediaItem = MediaItem.fromUri(mp3Url_1)
            mExoPlayer?.setMediaItem(mediaItem)
            mExoPlayer?.prepare()
        }

        //加载多个资源
        binding.loadMore.setOnClickListener {
            //加载本地资源
            val mediaItem1: MediaItem = MediaItem.fromUri(mp3Url_1)

            val uri = RawResourceDataSource.buildRawResourceUri(R.raw.mp31)
            val mediaItem2: MediaItem = MediaItem.fromUri(uri)
            mExoPlayer?.setMediaItem(mediaItem1)
            mExoPlayer?.setMediaItem(mediaItem2)
            mExoPlayer?.prepare()
        }

        //播放
        binding.play.setOnClickListener {
            mExoPlayer?.play()
        }

        //暂停
        binding.pause.setOnClickListener {
            mExoPlayer?.pause()
        }

        //停止
        binding.stop.setOnClickListener {
            mExoPlayer?.stop()
        }

        //是否资源
        binding.release.setOnClickListener {
            mExoPlayer?.release()
        }
    }

    private val mPlayerListener = object : Player.Listener {
        override fun onPlaybackStateChanged(state: Int) {
            super.onPlaybackStateChanged(state)
            if (Player.STATE_ENDED == state) {
                //播放结束
                Log.d("zyj-", "播放结束")
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        //是否资源
        mExoPlayer?.release()
    }

    companion object {
        const val mp3Url_1 = "http://downsc.chinaz.net/Files/DownLoad/sound1/201906/11582.mp3"
    }
}